/**
 * Created by Yun on 2015-12-13.
 */
import { browserHistory } from 'react-router';
import {emit} from '../utils/pubsub';

let accessToken = null;
const contentType = 'application/json';
export const rootUrl = "/api";

export function saveAccessToken(token) {
  window.localStorage.adminToken = token;
}

export async function checkAccessToken(){
  var token = window.localStorage.adminToken;

  var ret = await get('/admin/user/checkadmin');
  if (ret.ok){
    return true;
  }
  return false;
}

async function request(url, options, needProxy = true) {
  options = options || {method: 'GET'};
  options.headers = options.headers || {};
  if (needProxy){
    options.headers['x-accesstoken'] = window.localStorage.adminToken;
    options.credentials = 'include';
  }

  const resp = await fetch(needProxy?(rootUrl + url):url, options);
  const json = await resp.json();

  if (resp.status === 200){
    return {
      status: resp.status,
      ...json
    }
  }else{
    return {
      ok:0,
      status: resp.status
    }
  }
  //未做出错处理
  /*
  if (resp.status === 200) {
    return json;
  } else {
    if (resp.status === 401) {

      if (accessToken) {
        accessToken = null;
        emit('/user/logout');
      }
    }
    const err = new Error(json.message);
    err.status = resp.status;
    err.code = json.code;
    err.origin = json;
    throw err;
  }*/
}

export function get(url, options) {
  return request(url, options)
}

export function apiDelete(url, options) {
  return request(url, {
    method: 'DELETE',
    ...options,
  })
}

export function post(url, data, options) {

  return request(url, {
    method: 'POST',
    headers: {
      'Content-Type': contentType
    },
    body: JSON.stringify(data),
    ...options
  })
}

export function postWithFormData(url, data, options){

  return request(url, {
    method: 'POST',
    headers:{
    },
    body: data,
    ...options
  }, false);

}

export function put(url, data, options) {

  return request(url, {
    method: 'PUT',
    headers: {
      'Content-Type': contentType,
    },
    body: body,
    ...options
  })
}
